package net.hangar5.xmlrpc;

/* RespParser.java

The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.

The Original Code is "Hangar5 XMLRPC Library".

The Initial Developer of the Original Code is James D. Rudnicki.
Portions created by James D. Rudnicki are
Copyright (C) 2001.  All Rights Reserved.

Contributor(s):
*/
import java.util.*;


/** Dissects XML-RPC call data into method name and parameters.
 */
public class RespParser extends XmlParser {

  static protected final String tagMresponseO = "<methodResponse>";
	static protected final String tagFaultO = "<fault>";
  static protected final int sizeMresponseO = 16;
  static protected final String tagMresponseC = "</methodResponse>";
  static protected final int sizeMresponseC = 17;

  protected Object oRet;


public RespParser(String s) {
	super(s);
	oRet = null;
	return;
}
public RespParser(StringBuffer sb)
{
	super(sb);
	oRet = null;
}

  public Object getReturn()
  {
	return oRet;
  }

  public Object parseXml() throws RpcException
  {
	int i1, i2, j1, j2;
	boolean bIsFault = false;

	oRet = null;
	i1 = strSearch.indexOf(tagMresponseO, nIxProcThru);
	if( i1 < 0)
        {
		throw new RpcException(RpcException.GENERIC, RpcException.SGENERIC);
	}

	i2 = strSearch.indexOf(tagMresponseC, i1 + sizeMresponseO);
	if( i2 < 0 )
        {
		throw new RpcException(RpcException.GENERIC, RpcException.SGENERIC);
	}

	/* If there is a fault element, set flag to be
	used after response is parsed */
	j1 = strSearch.indexOf( tagFaultO, i1+sizeMresponseO );
	if( (j1 > i1) & (j1 < i2) )
        {
		bIsFault = true;
	}
	j1 = strSearch.indexOf(tagValueO, i1+sizeMresponseO );
	j2 = strSearch.lastIndexOf( tagValueC, i2);
	oRet = parseValue(j1 + sizeValueO, j2);
	/* convert structure to RpcException */
	final String FAULTCODE = new String( "faultCode" );
	final String FAULTSTRING = new String( "faultString" );
	if( bIsFault )
        {
		Hashtable h = (Hashtable)oRet;
		if( h.containsKey( FAULTCODE ) & h.containsKey( FAULTSTRING ) )
                {
			int n = ((Integer)h.get( FAULTCODE )).intValue();
			String s = (String)h.get( FAULTSTRING );
			oRet = null;
			throw new RpcException( n, s );
		}
		else
                {
			throw new RpcException(RpcException.GENERIC, RpcException.SGENERIC);
		}
	}
	return oRet;
}
} // end of class
